import { Toast } from 'vant';

/**
 * 日期时间转时间差格式
 * @param  string  datetime  日期时间
 * @return string
 */
export function datetimeFormat(datetime)
{
    if (!datetime)
        return '-';
    
    var diff = new Date().getTime() - Date.parse(new Date(datetime)),
        minute = 1000 * 60,
        hour   = minute * 60,
        day    = hour * 24,
        month  = day * 30,
        monthC = diff / month,
        weekC  = diff / (7 * day),
        dayC   = diff / day,
        hourC  = diff / hour,
        minC   = diff / minute;

    switch (true)
    {
        case monthC > 12:
            return parseInt(monthC / 12) + '年前';

        case monthC >= 1:
            return parseInt(monthC) + '月前';

        case weekC >= 1:
            return parseInt(weekC) + '周前';

        case dayC >= 1:
            return parseInt(dayC) + '天前';

        case hourC >= 1:
            return parseInt(hourC) + '小时前';

        case minC > 1:
            return parseInt(minC) + '分钟前';

        case minC <= 1:
            return '刚刚';

        default: 
            return datetime;
    }
}


/**
 * 表单验证
 * @param  {[type]} type  验证类型
 * @param  {[type]} value 输入值
 * @param  {[type]} compare 对比值
 * return Promise
 */
export function validate(type,value,compare)
{
    switch(type)
    {
        case "email":
            if( value == "" || !(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)) )
            {
                return new Promise(() => { value ? Toast("邮箱格式错误") : Toast("邮箱不能为空")});
            } 
            break;
        case "phone":
            if( value == "" || !(/^(1[3-9][0-9])\d{8}$/ig.test(value)) )
            {
                return new Promise(() => { value ? Toast("手机号格式错误") : Toast("手机号不能为空")});
            } 
            break;

        case "password":
            if( value == "" || value.length < 6 )
            {
                return new Promise(() => { value ? Toast("密码长度不能小于6位数") : Toast("密码不能为空") });
            }
            break;                        
        case "password2":
            if( value == "" || value != compare )
            {
                return new Promise(() => {value ? Toast("两次密码不一致") : Toast("确认密码不能为空")});
            }
            break;
        case "code":
            if( value == "" || value.length < 6 )
            {
                return new Promise(() => { value ? Toast("验证码有误") : Toast("验证码不能为空") });
            }
            break;                  
    } 
}

/**
 * 加载外部JS文件
 *
 * @param  string    src        请求地址
 * @param  function  callback   回调函数
 */
export function loadScript(src, callback)
{
    var script = document.createElement('script');
    var loaded = false;

    script.setAttribute('src', src);
    if (callback)
	{
        script.onload = function()
		{
            if (!loaded)
			{
                callback();
            }

            loaded = true;
        };
    }
    document.getElementsByTagName('head')[0].appendChild(script);
}


/**
 * 上传图片
 * @param  {[type]}   id       上传图片ID
 * @param  {Function} callback 回调函数
 * @return Promise
 */
export function uploadAvatar (id, callback) {
    const file = document.getElementById(id).files[0];
    let reader = new FileReader();
    let imgUrlBase64;
    if (file) {
       // 将文件以Data URL形式读入页面
        imgUrlBase64 = reader.readAsDataURL(file);
        console.log(imgUrlBase64);
        reader.onload =  e => {
            //截取base64码部分
            let img_file = reader.result.substring(reader.result.indexOf(",") + 1).length;
            if (reader.result.length <= 0) {    
                return false;
            } else {
                //这里调接口，把reader.result传过去
                callback(reader.result); 
                return Toast('上传成功')
            }
        }
    }
};

/**
 * 时间格式化
 * @param  {[type]} date 需要转换的时间
 * @param  {[type]} fmt  转换后的时间格式   如'yyyy-MM-dd'
 * @return Promise
 */
 export function formatDate (date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
 };
 function padLeftZero (str) {
    return ('00' + str).substr(str.length);
 };


/**
 * h5 app 交互
 * @param {Boolean} isSend       状态类型
 * @param {[type]}  name         方法名
 * @param {[type]}  parameter    参数
 * @param {[type]}  dataCallback 回调
 */
 export function App(isSend,name,parameter,dataCallback)
 {
    function setupWebViewJavascriptBridge(callback) {
        if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
        if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        // WVJBIframe.src = 'https://__bridge_loaded__';
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(() => { document.documentElement.removeChild(WVJBIframe) }, 0)
    }
    setupWebViewJavascriptBridge(bridge => {
        //js调用app方法 
        if (isSend) {
            bridge.callHandler(name, parameter, response => {
                dataCallback(response)
            })
        }
        else 
        {
            // app调用js方法
            bridge.registerHandler(name, (data, responseCallback) => {
                dataCallback(data, responseCallback)
            })
        }
    })
 }
// function testA() {
//     App(true,{'name':'123'},'jumpAPP',function(response) {
//         console.log(response)
//     })
//     App(false,'','asAPP',function(data, responseCallback) {
//         console.log(data)
//         responseCallback({'name':'123'})
//     })
// }
